package me.zhengjie.modules.weixin.processor.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import me.zhengjie.modules.weixin.dto.WeChatAccount;
import me.zhengjie.modules.weixin.enums.WeChatMsgTypeEnum;
import me.zhengjie.modules.weixin.message.AnalyzerReplyMessage;
import me.zhengjie.modules.weixin.message.reply.AbstractReplyMessage;
import me.zhengjie.modules.weixin.processor.AbstractProcessor;

import java.util.ArrayList;
import java.util.Map;

public class ChatsProcessor extends AbstractProcessor {

    public ChatsProcessor() {

    }

    public ChatsProcessor(WeChatAccount account, AnalyzerReplyMessage reply) {
        this.account = account;
        this.reply = reply;
    }

    ArrayList<String> allowMsgTypes = Lists.newArrayList(
            WeChatMsgTypeEnum.text.name(),
            WeChatMsgTypeEnum.image.name(),
            WeChatMsgTypeEnum.location.name(),
            WeChatMsgTypeEnum.link.name()
    );

    @Override
    public AbstractReplyMessage process() throws Exception {

        Map<String, Object> receiveMsg = reply.getReceiveMsg();

        String msgType = (String) receiveMsg.get("MsgType");
        WeChatMsgTypeEnum msgTypeEnum = WeChatMsgTypeEnum.get(msgType);

        if (!allowMsgTypes.contains(msgType)) {
            return respText("抱歉,系统仅支持 文字，图片，地理位置，链接类型的消息！");
        }

        int close = 0;
        String content = "";

        switch (msgTypeEnum) {
            case text:
                content = (String) receiveMsg.get("Content");
                if ("关闭".equals(content)) {
                    content = "<span class=\"text-danger\">系统消息：粉丝关闭了对话</span>";
                    close = 1;
                }
                break;
            case image:
                content = (String) receiveMsg.get("PicUrl");
                break;
            case location:
                JSONObject obj = new JSONObject();
                obj.put("location_x", receiveMsg.get("Location_X"));
                obj.put("location_y", receiveMsg.get("Location_Y"));
                obj.put("scale", receiveMsg.get("Scale"));

                break;
            case link:
                content = (String) receiveMsg.get("Url");
                break;
            default:
                break;
        }

        refreshContext(300);
        if (close == 1) {
            endContext();
            return respText("您成功关闭回话。");
        }
        return respText("");
    }
}
